/**
 * 加载动态路由
 */

import router from '@/router'
import store from '@/store'
import Login from '@/views/Login.vue'
import VueRouter from 'vue-router'

export default function initRouter(routerData) {
    //重置路由
    resetRouter()

    //获取路由和菜单信息
    const data = transeArrayToTree(routerData)

    //动态添加路由
    addRoutes(data.router, "")

    //将菜单信息存放到vuex中
    store.dispatch("setMenuData", data.menu)
}

//重置路由
function resetRouter() {
    const newRouter = new VueRouter({
        routes: [
            {
                path: '/',
                redirect: '/welcome'
            },
            {
                path: '/login',
                name: 'login',
                meta: {
                    title: "登录"
                },
                component: Login
            }
        ]
    })
    router.matcher = newRouter.matcher
}

//处理路由数据为树形结构
function transeArrayToTree(arr) {
    let router = []
    let menu = []

    arr.forEach(item => {
        if (item.path) {
            router.push(item)
        }
        if (item.pmenu !== null) {
            menu.push(item)
        }
    })

    let routerMap = router.reduce((pre, item) => {
        pre[item.id] = item
        return pre
    }, {})

    let menuMap = menu.reduce((pre, item) => {
        pre[item.id] = item
        return pre
    }, {})

    router = router.reduce((pre, item) => {
        if (item.pid) {
            if (!routerMap[item.pid].children) {
                pre[item.pid].children = []
            }
            pre[item.pid].children.push(item)
        } else {
            pre[item.id] = item
        }
        return pre
    }, {})

    router = Object.keys(router).reduce((pre, item) => {
        pre.push(router[item])
        return pre
    }, [])

    menu = menu.reduce((pre, item) => {
        if (item.pmenu) {
            if (!menuMap[item.pmenu].children) {
                pre[item.pmenu].children = []
            }
            pre[item.pmenu].children.push(item)
        } else {
            pre[item.id] = item
        }
        return pre
    }, {})

    menu = Object.keys(menu).reduce((pre, item) => {
        pre.push(menu[item])
        return pre
    }, [])

    return {
        router,
        menu
    }
}

//获取路由信息
function getRouteItem(item) {
    return {
        path: item.path,
        name: item.cpn,
        component: () => import('@/views/' + item.cpn),
        meta: {
            icon: item.icon,
            title: item.title
        }
    }
}

//添加动态路由
function addRoutes(route, parent) {
    route.forEach(item => {
        router.addRoute(parent, getRouteItem(item))
        if (item.children) {
            addRoutes(item.children, item.cpn)
        }
    })
}